<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="keyword"  content="">
    <link rel="shortcut icon" href="/img/logo.png">
    <!-- Place this tag in your head or just before your close body tag. -->
    <script async defer src="https://buttons.github.io/buttons.js"></script>
    <title>
        
          浅谈反射 - 宋正兵的博客 | zbsong Blog
        
    </title>

    <link rel="canonical" href="zbsong.top/article/jdk学习之路—反射/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS --> 
    <link rel="stylesheet" href="/css/beantech.min.css">

    <link rel="stylesheet" href="/css/donate.css">
    
    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css">

    <link rel="stylesheet" href="/css/widget.css">

    <link rel="stylesheet" href="/css/rocket.css">

    <link rel="stylesheet" href="/css/signature.css">

    <link rel="stylesheet" href="/css/toc.css">

    <!-- Custom Fonts -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">


    <!-- Hux Delete, sad but pending in China
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
    css'>
    -->


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- ga & ba script hoook -->
    <script></script>
</head>


<!-- hack iOS CSS :active style -->
<body ontouchstart="">
	<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->
<style type="text/css">
    header.intro-header{
        
            background-image: url('https://api.dujin.org/bing/1920.php')
            /*post*/
        
    }
    
</style>

<header class="intro-header" >
    <!-- Signature -->
    <div id="signature">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                
                    <div class="post-heading">
                        <div class="tags">
                            
                              <a class="tag" href="/tags/#jdk学习之路" title="jdk学习之路">jdk学习之路</a>
                            
                        </div>
                        <h1>浅谈反射</h1>
                        <!-- <h2 class="subheading">谈谈反射机制以及发射在简单java类属性自动配置上的应用</h2> -->
                        <span class="meta">
                            宋正兵 on
                            2020-12-09
                        </span>
                    </div>
                


                </div>
            </div>
        </div>
    </div>
</header>

    <!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">songzblink</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/">主页</a>
                    </li>
					<li>
                        <a href="/archive/">归档</a>
                    </li>
					<li>
                        <a href="/tags/">标签</a>
                    </li>
					<li>
                        <a href="/about/">关于</a>
                    </li>
					<!--
					修改about在前面的问题
                    
                        
                    
                        
                        <li>
                            <a href="/about/">关于</a>
                        </li>
                        
                    
                        
                        <li>
                            <a href="/archive/">归档</a>
                        </li>
                        
                    
                        
                        <li>
                            <a href="/tags/">标签</a>
                        </li>
                        
                    
                    -->
                </ul>
            </div>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    var $body   = document.body;
	// querySelector 获取文档中 id="demo" 的元素
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>


    <!-- Main Content -->
    <!-- Modify by Yu-Hsuan Yen -->

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

            <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

				
                <h2 id="定义">定义</h2>
<p>Java 反射机制是在运行状态中，对于任意一个类，都能够知道这个类的所有属性和方法；对于任意一个对象，都能够调用它的任意方法和属性；这种动态获取信息以及动态调用对象方法的功能称为 Java 语言的反射机制。</p>
<h2 id="获取一个类的实例化对象的三种方式">获取一个类的实例化对象的三种方式</h2>
<p>（1）Object 类支持的 getClass() 方法：<code>public final Class&lt;?&gt;getClass()</code></p>
<p>Object 类可以根据<strong>实例化</strong>对象获取 Class 对象，必须是在产生指定类对象后才可以获得。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;&#125;<span class="comment">// 采用自定义的程序类</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JavaAPIDemo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		Person per = <span class="keyword">new</span> Person(); <span class="comment">// 已经存在有指定类的实例化对象</span></span><br><span class="line">		Class&lt;? extends Person&gt; cls = per.getClass();</span><br><span class="line">		System.out.println(cls.getName());<span class="comment">// 获取类的完整名称</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>（2）JVM 直接支持，采用“类.class”的形式实例化。特点是如果采用此模式，则必须导入程序所对应的开发包。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;&#125;<span class="comment">// 采用自定义的程序类</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JavaAPIDemo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		Class&lt;? extends Person&gt; cls = Person.class;</span><br><span class="line">		System.out.println(cls.getName());<span class="comment">// 获取类的完整名称</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>（3）Class 类支持有一个 static 方法，可以加载类：<code>public static Class&lt;?&gt; forName(String className) throws ClassNotFoundException</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JavaAPIDemo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">		Class&lt;?&gt; cls = Class.forName(<span class="string">"cn.my.vo.Person"</span>);</span><br><span class="line">		System.out.println(cls.getName());<span class="comment">// 获取类的完整名称</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// Person类放在cn.my.vo开发包中</span></span><br></pre></td></tr></table></figure>
<h2 id="通过反射实例化对象">通过反射实例化对象</h2>
<p>获取 Class 对象的最大意义在于 Class 类里面提供有一个对象的反射实例化方法，它替代了关键字 new：</p>
<p>在 JDK 1.9之前：<code>public T newInstance() throws InstantiationException, IllegalAccessException</code></p>
<p>观察下面实例可以发现，通过反射实现的对象实例化处理，依然要调用类中的无参构造方法，其本质等价于“类 对象 = new 类()”，相当于隐藏了关键字 new 而直接使用字符串进行了替代。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* package cn.my.vo中Person.java */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">	<span class="comment">// 任何情况下如果要实例化对象则一定要调用类中的构造方法</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">Person</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		System.out.println(<span class="string">"*****Person类构造方法*****"</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="string">"一个Person类"</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* JavaAPIDemo.java */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JavaAPIDemo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">		Class&lt;?&gt; cls = Class.forName(<span class="string">"cn.my.vo.Person"</span>);</span><br><span class="line">		Object obj = cls.newInstance();<span class="comment">// 实例化对象，JDK 1.9后被废除了</span></span><br><span class="line">		System.out.println(obj); <span class="comment">// 输出对象调用toString()方法</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* 执行结果</span></span><br><span class="line"><span class="comment">【cls.newInstance()、关键字new】*****Person类构造方法*****</span></span><br><span class="line"><span class="comment">【System.out.println(obj)】一个Person类</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>
<p>在 JDK 1.9 之后，newInstance() 被替代了：<code>clazz.getDeclaredConstructor().newInstance()</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JavaAPIDemo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">		Class&lt;?&gt; cls = Class.forName(<span class="string">"cn.my.vo.Person"</span>);</span><br><span class="line">		Object obj = cls.getDeclaredConstructor().newInstance();</span><br><span class="line">		System.out.println(obj); <span class="comment">// 输出对象调用toString()方法</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="反射获取类的基本信息">反射获取类的基本信息</h2>
<p>利用 Class类 可以获取类之中的基本信息，参考<a href="https://zbsong.top/article/jdk%E5%AD%A6%E4%B9%A0%E4%B9%8B%E8%B7%AF%E2%80%94%E5%8F%8D%E5%B0%84%E6%9C%BA%E5%88%B6%E7%9A%84%E7%9B%B8%E5%85%B3%E7%B1%BB/">反射机制的相关类</a>。</p>
<h2 id="应用反射与简单java类对象属性的自动设置">应用：反射与简单Java类对象属性的自动设置</h2>
<p>在传统的对象实例化并设置数据的操作过程之中，设置数据的部分是最麻烦的，如果类里面提供有大量的属性，那么对程序的赋值来说会出现一堆的setter()方法，会带来大量的重复操作。</p>
<p>反射机制可以根据其自身的特点（Object类直接操作属性或方法）实现相同功能类的重复操作的抽象处理。</p>
<h3 id="属性的自动设置">属性的自动设置</h3>
<p>设计的基本结构</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ClassInstanceFactory</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">ClassInstanceFactory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 实例化对象的创建方法，该对象可以根据传入的字符串结构“属性:内容|属性:内容”</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> clazz 要进行反射实例化Class类对象，有Class就可以反射实例化对象</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> value 要设置给对象的属性内容</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> 一个已经配置好属性内容的简单Java类对象</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">T <span class="title">create</span><span class="params">(Class&lt;?&gt; clazz,String value)</span></span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="单级属性配置">单级属性配置</h3>
<p>单级属性即所给出的属性数据类型没有其他的引用关系，只描述了本类的对象，单级属性设置需要处理两件事：</p>
<ul>
<li>通过反射进行指定类对象的实例化处理</li>
<li>进行内容的设置（Field属性类型、方法名称、要设置的内容）</li>
</ul>
<p>1、定义 StringUtils 实现首字母大写功能</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StringUtils</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">initcap</span><span class="params">(String str)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (str == <span class="keyword">null</span> || <span class="string">""</span>.contentEquals(str)) &#123;</span><br><span class="line">			<span class="keyword">return</span> str;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (str.length() == <span class="number">1</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span> str.toUpperCase();</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="keyword">return</span> str.substring(<span class="number">0</span>, <span class="number">1</span>).toUpperCase() + str.substring(<span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>2、定义 BeanUtils 工具类，该工具类主要实现属性的设置。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BeanUtils</span> </span>&#123; <span class="comment">// 进行Bean处理的类</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">BeanUtils</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 实现指定对象的属性设置</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> obj   要进行反射操作的实例化对象</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> value 包含有指定内容的字符串，格式为“属性:内容|属性:内容”</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">setValue</span><span class="params">(Object obj, String value)</span> </span>&#123;</span><br><span class="line">		String[] results = value.split(<span class="string">"\\|"</span>); <span class="comment">// 按照“|”进行每一组属性的拆分</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> x = <span class="number">0</span>; x &lt; results.length; x++) &#123; <span class="comment">// 循环设置属性内容</span></span><br><span class="line">			<span class="comment">// attval[0]保存属性名称，attval[1]保存属性内容</span></span><br><span class="line">			String[] attval = results[x].split(<span class="string">":"</span>);<span class="comment">// 获取属性名称与属性内容</span></span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				Field field = obj.getClass().getDeclaredField(attval[<span class="number">0</span>]);</span><br><span class="line">				Method setMethod = obj.getClass().getDeclaredMethod(<span class="string">"set"</span> + StringUtils.initcap(attval[<span class="number">0</span>]),</span><br><span class="line">						field.getType());</span><br><span class="line">				setMethod.invoke(obj, attval[<span class="number">1</span>]); <span class="comment">// 调用setter方法设置内容</span></span><br><span class="line">			&#125; <span class="keyword">catch</span> (Exception e) &#123;&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>3、ClassInstanceFactory 负责实例化对象并且调用 BeanUtils 类实现属性内容的设置</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.lang.reflect.Field;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Method;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JavaAPIDemo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">		String value = <span class="string">"ename:Smith|job:Clerk"</span>;</span><br><span class="line">		Emp emp = ClassInstanceFactory.create(Emp.class, value);</span><br><span class="line">		System.out.println(<span class="string">"姓名："</span> + emp.getEname() + <span class="string">"、职位："</span> + emp.getJob());</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ClassInstanceFactory</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">ClassInstanceFactory</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 实例化对象的创建方法，该对象可以根据传入的字符串结构“属性:内容|属性:内容”</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> clazz 要进行反射实例化Class类对象，有Class就可以反射实例化对象</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> value 要设置给对象的属性内容</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> 一个已经配置好属性内容的简单Java类对象</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">T <span class="title">create</span><span class="params">(Class&lt;?&gt; clazz, String value)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">try</span> &#123;<span class="comment">// 如果想采用反射进行简单Java类对象属性设置时，类中必须要有无参构造</span></span><br><span class="line">			Object obj = clazz.getDeclaredConstructor().newInstance();</span><br><span class="line">			BeanUtils.setValue(obj, value); <span class="comment">// 通过反射设置属性</span></span><br><span class="line">			<span class="keyword">return</span> (T) obj; <span class="comment">// 返回对象</span></span><br><span class="line">		&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">			e.printStackTrace(); <span class="comment">// 如果此时真的出现了错误，本质上抛出异常也无效</span></span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StringUtils</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">initcap</span><span class="params">(String str)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (str == <span class="keyword">null</span> || <span class="string">""</span>.contentEquals(str)) &#123;</span><br><span class="line">			<span class="keyword">return</span> str;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (str.length() == <span class="number">1</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span> str.toUpperCase();</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="keyword">return</span> str.substring(<span class="number">0</span>, <span class="number">1</span>).toUpperCase() + str.substring(<span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BeanUtils</span> </span>&#123; <span class="comment">// 进行Bean处理的类</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">BeanUtils</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 实现指定对象的属性设置</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> obj   要进行反射操作的实例化对象</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> value 包含有指定内容的字符串，格式为“属性:内容|属性:内容”</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">setValue</span><span class="params">(Object obj, String value)</span> </span>&#123;</span><br><span class="line">		String[] results = value.split(<span class="string">"\\|"</span>); <span class="comment">// 按照“|”进行每一组属性的拆分</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> x = <span class="number">0</span>; x &lt; results.length; x++) &#123; <span class="comment">// 循环设置属性内容</span></span><br><span class="line">			<span class="comment">// attval[0]保存属性名称，attval[1]保存属性内容</span></span><br><span class="line">			String[] attval = results[x].split(<span class="string">":"</span>);<span class="comment">// 获取属性名称与属性内容</span></span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				Field field = obj.getClass().getDeclaredField(attval[<span class="number">0</span>]);</span><br><span class="line">				Method setMethod = obj.getClass().getDeclaredMethod(<span class="string">"set"</span> + StringUtils.initcap(attval[<span class="number">0</span>]),</span><br><span class="line">						field.getType());</span><br><span class="line">				setMethod.invoke(obj, attval[<span class="number">1</span>]); <span class="comment">// 调用setter方法设置内容</span></span><br><span class="line">			&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">				e.printStackTrace();</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Emp</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> String ename;</span><br><span class="line">	<span class="keyword">private</span> String job;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getEname</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> ename;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setEname</span><span class="params">(String ename)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.ename = ename;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getJob</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> job;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setJob</span><span class="params">(String job)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.job = job;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="多种数据类型的属性配置">多种数据类型的属性配置</h3>
<p>实际开发之中会面对类中属性类型多样，要实现各种数据类型的配置，在 BeanUtils 类中完成一系列的处理方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 实现属性类型转换处理</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> type  属性类型，通过Field获取的</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> value 属性的内容，传入的都是字符串，需要将其变为指定类型</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> 转换后的数据</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> Object <span class="title">convertAttributeValue</span><span class="params">(String type, String value)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//		System.out.println("type = " + type + "、value = " + value);</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="string">"long"</span>.equals(type) || <span class="string">"Long"</span>.equals(type)) &#123; <span class="comment">// 长整型</span></span><br><span class="line">        <span class="keyword">return</span> Long.parseLong(value);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">"int"</span>.equals(type) || <span class="string">"java.lang.int"</span>.equals(type)) &#123;</span><br><span class="line">        <span class="keyword">return</span> Integer.parseInt(value);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">"double"</span>.equals(type) || <span class="string">"java.lang.double"</span>.equals(type)) &#123;</span><br><span class="line">        <span class="keyword">return</span> Double.parseDouble(value);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">"java.util.Date"</span>.equals(type)) &#123;</span><br><span class="line">        SimpleDateFormat sdf = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (value.matches(<span class="string">"\\d&#123;4&#125;-\\d&#123;2&#125;-\\d&#123;2&#125;"</span>)) &#123; <span class="comment">// 日期类型</span></span><br><span class="line">            sdf = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd"</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (value.matches(<span class="string">"\\d&#123;4&#125;-\\d&#123;2&#125;-\\d&#123;2&#125; \\d&#123;2&#125;:\\d&#123;2&#125;:\\d&#123;2&#125;"</span>)) &#123;</span><br><span class="line">            sdf = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Date();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> sdf.parseObject(value);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Date(); <span class="comment">// 当前日期</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="级联对象实例化">级联对象实例化</h3>
<p>如果现在给定的类对象之中存在有其它的引用的级联关系时，需要多级设置。如一个雇员属于一个部门，一个部门属于一个公司，简单 Java 类的基本定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Company</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> String name;</span><br><span class="line">	<span class="keyword">private</span> Date creatDate;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dept</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> String dname;</span><br><span class="line">	<span class="keyword">private</span> String loc;</span><br><span class="line">	<span class="keyword">private</span> Company company;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Emp</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">long</span> empno;</span><br><span class="line">	<span class="keyword">private</span> String ename;</span><br><span class="line">	<span class="keyword">private</span> String job;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">double</span> salary;</span><br><span class="line">	<span class="keyword">private</span> Date hiredate;</span><br><span class="line">	<span class="keyword">private</span> Dept dept;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果要对 Emp 进行操作，则应该使用“.”作为级联关系的处理。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">dept.dname:财务部：   		Emp类实例化对象.getDept().setDname(&quot;财务部&quot;)</span><br><span class="line">dept.company.name:BELTA:    Emp类实例化对象.getDept().getCompany().setName(&quot;BELTA&quot;)</span><br></pre></td></tr></table></figure>
<p>考虑到代码的简洁性，应该通过级联的配置自动实现类中属性的实例化。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">String value = <span class="string">"empno:7369|ename:Smith|job:Clerk|salary:9999|hiredate:1989-10-10"</span></span><br><span class="line">    + <span class="string">"dept.dname:财务部|dept.company.name:BELTA"</span>;</span><br></pre></td></tr></table></figure>
<p>现在的属性存在有多级的关系，那么对于多级的关系就必须与单级的配置区分开。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BeanUtils</span> </span>&#123; <span class="comment">// 进行Bean处理的类</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">BeanUtils</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 实现指定对象的属性设置</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> obj   要进行反射操作的实例化对象</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> value 包含有指定内容的字符串，格式为“属性:内容|属性:内容”</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">setValue</span><span class="params">(Object obj, String value)</span> </span>&#123;</span><br><span class="line">		String[] results = value.split(<span class="string">"\\|"</span>); <span class="comment">// 按照“|”进行每一组属性的拆分</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> x = <span class="number">0</span>; x &lt; results.length; x++) &#123; <span class="comment">// 循环设置属性内容</span></span><br><span class="line">			<span class="comment">// attval[0]保存属性名称，attval[1]保存属性内容</span></span><br><span class="line">			String[] attval = results[x].split(<span class="string">":"</span>);<span class="comment">// 获取属性名称与属性内容</span></span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				<span class="keyword">if</span> (attval[<span class="number">0</span>].contains(<span class="string">"."</span>)) &#123; <span class="comment">// 多级配置</span></span><br><span class="line">					String[] temp = attval[<span class="number">0</span>].split(<span class="string">"\\."</span>);</span><br><span class="line">					Object currentObject = obj;</span><br><span class="line">					<span class="comment">// 最后一位肯定是指定类中的属性名称，所以不在本次实例化处理范围之内</span></span><br><span class="line">					<span class="keyword">for</span> (<span class="keyword">int</span> y = <span class="number">0</span>; y &lt; temp.length - <span class="number">1</span>; y++) &#123; <span class="comment">// 实例化</span></span><br><span class="line">						<span class="comment">// 调用相应的getter方法，如果getter方法返回了null表示该对象未实例化</span></span><br><span class="line">						Method getMethod = currentObject.getClass()</span><br><span class="line">								.getDeclaredMethod(<span class="string">"get"</span> + StringUtils.initcap(temp[y]));</span><br><span class="line">						Object tempObject = getMethod.invoke(currentObject);</span><br><span class="line">						<span class="keyword">if</span> (tempObject == <span class="keyword">null</span>) &#123; <span class="comment">// 该对象现在并没有实例化</span></span><br><span class="line">							Field field = currentObject.getClass().getDeclaredField(temp[y]);<span class="comment">// 获取属性类型</span></span><br><span class="line">							Method method = currentObject.getClass()</span><br><span class="line">									.getDeclaredMethod(<span class="string">"set"</span> + StringUtils.initcap(temp[y]), field.getType());</span><br><span class="line">							Object newObject = field.getType().getConstructor().newInstance();</span><br><span class="line">							method.invoke(currentObject, newObject);</span><br><span class="line">							currentObject = newObject;</span><br><span class="line">						&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">							currentObject = tempObject;</span><br><span class="line">						&#125;</span><br><span class="line">					&#125;</span><br><span class="line">				&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">					Field field = obj.getClass().getDeclaredField(attval[<span class="number">0</span>]);</span><br><span class="line">					Method setMethod = obj.getClass().getDeclaredMethod(<span class="string">"set"</span> + StringUtils.initcap(attval[<span class="number">0</span>]),</span><br><span class="line">							field.getType());</span><br><span class="line">					Object convertValue = BeanUtils.convertAttributeValue(field.getType().getName(), attval[<span class="number">1</span>]);</span><br><span class="line">					setMethod.invoke(obj, convertValue); <span class="comment">// 调用setter方法设置内容</span></span><br><span class="line">				&#125;</span><br><span class="line">			&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 实现属性类型转换处理</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> type  属性类型，通过Field获取的</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> value 属性的内容，传入的都是字符串，需要将其变为指定类型</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> 转换后的数据</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">static</span> Object <span class="title">convertAttributeValue</span><span class="params">(String type, String value)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (<span class="string">"long"</span>.equals(type) || <span class="string">"Long"</span>.equals(type)) &#123; <span class="comment">// 长整型</span></span><br><span class="line">			<span class="keyword">return</span> Long.parseLong(value);</span><br><span class="line">		&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">"int"</span>.equals(type) || <span class="string">"java.lang.int"</span>.equals(type)) &#123;</span><br><span class="line">			<span class="keyword">return</span> Integer.parseInt(value);</span><br><span class="line">		&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">"double"</span>.equals(type) || <span class="string">"java.lang.double"</span>.equals(type)) &#123;</span><br><span class="line">			<span class="keyword">return</span> Double.parseDouble(value);</span><br><span class="line">		&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">"java.util.Date"</span>.equals(type)) &#123;</span><br><span class="line">			SimpleDateFormat sdf = <span class="keyword">null</span>;</span><br><span class="line">			<span class="keyword">if</span> (value.matches(<span class="string">"\\d&#123;4&#125;-\\d&#123;2&#125;-\\d&#123;2&#125;"</span>)) &#123; <span class="comment">// 日期类型</span></span><br><span class="line">				sdf = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd"</span>);</span><br><span class="line">			&#125; <span class="keyword">else</span> <span class="keyword">if</span> (value.matches(<span class="string">"\\d&#123;4&#125;-\\d&#123;2&#125;-\\d&#123;2&#125; \\d&#123;2&#125;:\\d&#123;2&#125;:\\d&#123;2&#125;"</span>)) &#123;</span><br><span class="line">				sdf = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">			&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">new</span> Date();</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				<span class="keyword">return</span> sdf.parseObject(value);</span><br><span class="line">			&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">new</span> Date(); <span class="comment">// 当前日期</span></span><br><span class="line">			&#125;</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="keyword">return</span> value;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Company</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> String name;</span><br><span class="line">	<span class="keyword">private</span> Date creatDate;</span><br><span class="line">    <span class="comment">// 构造、setter、getter</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dept</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> String dname;</span><br><span class="line">	<span class="keyword">private</span> String loc;</span><br><span class="line">	<span class="keyword">private</span> Company company;</span><br><span class="line">	<span class="comment">// 构造、setter、getter</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Emp</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">long</span> empno;</span><br><span class="line">	<span class="keyword">private</span> String ename;</span><br><span class="line">	<span class="keyword">private</span> String job;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">double</span> salary;</span><br><span class="line">	<span class="keyword">private</span> Date hiredate;</span><br><span class="line">	<span class="keyword">private</span> Dept dept;</span><br><span class="line">	<span class="comment">// 构造、setter、getter</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="级联属性设置">级联属性设置</h3>
<p>现在已经成功的实现级联的对象实例化处理，随后需要考虑级联的属性设置。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.lang.reflect.Field;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Method;</span><br><span class="line"><span class="keyword">import</span> java.text.SimpleDateFormat;</span><br><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JavaAPIDemo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">		String value = <span class="string">"empno:7369|ename:Smith|job:Clerk|salary:9999|hiredate:1989-10-10|"</span></span><br><span class="line">				+ <span class="string">"dept.dname:财务部|dept.company.name:BELTA"</span>;</span><br><span class="line">		Emp emp = ClassInstanceFactory.create(Emp.class, value);</span><br><span class="line">		System.out.println(<span class="string">"员工编号："</span> + emp.getEmpno() + <span class="string">"姓名："</span> + emp.getEname() + <span class="string">"、职位："</span> + emp.getJob() + <span class="string">"、工资"</span></span><br><span class="line">				+ emp.getSalary() + <span class="string">"、入职日期"</span> + emp.getHiredate());</span><br><span class="line">		System.out.println(emp.getDept().getDname());</span><br><span class="line">		System.out.println(emp.getDept().getCompany().getName());</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ClassInstanceFactory</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">ClassInstanceFactory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 实例化对象的创建方法，该对象可以根据传入的字符串结构“属性:内容|属性:内容”</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> clazz 要进行反射实例化Class类对象，有Class就可以反射实例化对象</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> value 要设置给对象的属性内容</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> 一个已经配置好属性内容的简单Java类对象</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">T <span class="title">create</span><span class="params">(Class&lt;?&gt; clazz, String value)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">try</span> &#123;<span class="comment">// 如果想采用反射进行简单Java类对象属性设置时，类中必须要有无参构造</span></span><br><span class="line">			Object obj = clazz.getDeclaredConstructor().newInstance();</span><br><span class="line">			BeanUtils.setValue(obj, value); <span class="comment">// 通过反射设置属性</span></span><br><span class="line">			<span class="keyword">return</span> (T) obj; <span class="comment">// 返回对象</span></span><br><span class="line">		&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">			e.printStackTrace(); <span class="comment">// 如果此时真的出现了错误，本质上抛出异常也无效</span></span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StringUtils</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">initcap</span><span class="params">(String str)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (str == <span class="keyword">null</span> || <span class="string">""</span>.contentEquals(str)) &#123;</span><br><span class="line">			<span class="keyword">return</span> str;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (str.length() == <span class="number">1</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span> str.toUpperCase();</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="keyword">return</span> str.substring(<span class="number">0</span>, <span class="number">1</span>).toUpperCase() + str.substring(<span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BeanUtils</span> </span>&#123; <span class="comment">// 进行Bean处理的类</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">BeanUtils</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 实现指定对象的属性设置</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> obj   要进行反射操作的实例化对象</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> value 包含有指定内容的字符串，格式为“属性:内容|属性:内容”</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">setValue</span><span class="params">(Object obj, String value)</span> </span>&#123;</span><br><span class="line">		String[] results = value.split(<span class="string">"\\|"</span>); <span class="comment">// 按照“|”进行每一组属性的拆分</span></span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> x = <span class="number">0</span>; x &lt; results.length; x++) &#123; <span class="comment">// 循环设置属性内容</span></span><br><span class="line">			<span class="comment">// attval[0]保存属性名称，attval[1]保存属性内容</span></span><br><span class="line">			String[] attval = results[x].split(<span class="string">":"</span>);<span class="comment">// 获取属性名称与属性内容</span></span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				<span class="keyword">if</span> (attval[<span class="number">0</span>].contains(<span class="string">"."</span>)) &#123; <span class="comment">// 多级配置</span></span><br><span class="line">					String[] temp = attval[<span class="number">0</span>].split(<span class="string">"\\."</span>);</span><br><span class="line">					Object currentObject = obj;</span><br><span class="line">					<span class="comment">// 最后一位肯定是指定类中的属性名称，所以不在本次实例化处理范围之内</span></span><br><span class="line">					<span class="keyword">for</span> (<span class="keyword">int</span> y = <span class="number">0</span>; y &lt; temp.length - <span class="number">1</span>; y++) &#123; <span class="comment">// 实例化</span></span><br><span class="line">						<span class="comment">// 调用相应的getter方法，如果getter方法返回了null表示该对象未实例化</span></span><br><span class="line">						Method getMethod = currentObject.getClass()</span><br><span class="line">								.getDeclaredMethod(<span class="string">"get"</span> + StringUtils.initcap(temp[y]));</span><br><span class="line">						Object tempObject = getMethod.invoke(currentObject);</span><br><span class="line">						<span class="keyword">if</span> (tempObject == <span class="keyword">null</span>) &#123; <span class="comment">// 该对象现在并没有实例化</span></span><br><span class="line">							Field field = currentObject.getClass().getDeclaredField(temp[y]);<span class="comment">// 获取属性类型</span></span><br><span class="line">							Method method = currentObject.getClass()</span><br><span class="line">									.getDeclaredMethod(<span class="string">"set"</span> + StringUtils.initcap(temp[y]), field.getType());</span><br><span class="line">							Object newObject = field.getType().getConstructor().newInstance();</span><br><span class="line">							method.invoke(currentObject, newObject);</span><br><span class="line">							currentObject = newObject;</span><br><span class="line">						&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">							currentObject = tempObject;</span><br><span class="line">						&#125;</span><br><span class="line">					&#125;</span><br><span class="line">					<span class="comment">// 进行属性内容设置</span></span><br><span class="line">					Field field = currentObject.getClass().getDeclaredField(temp[temp.length - <span class="number">1</span>]); <span class="comment">// 获取成员</span></span><br><span class="line">					Method setMethod = currentObject.getClass()</span><br><span class="line">							.getDeclaredMethod(<span class="string">"set"</span> + StringUtils.initcap(temp[temp.length - <span class="number">1</span>]), field.getType());</span><br><span class="line">					Object convertValue = BeanUtils.convertAttributeValue(field.getType().getName(), attval[<span class="number">1</span>]);</span><br><span class="line">					setMethod.invoke(currentObject, convertValue); <span class="comment">// 调用setter方法设置内容</span></span><br><span class="line">				&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">					Field field = obj.getClass().getDeclaredField(attval[<span class="number">0</span>]);</span><br><span class="line">					Method setMethod = obj.getClass().getDeclaredMethod(<span class="string">"set"</span> + StringUtils.initcap(attval[<span class="number">0</span>]),</span><br><span class="line">							field.getType());</span><br><span class="line">					Object convertValue = BeanUtils.convertAttributeValue(field.getType().getName(), attval[<span class="number">1</span>]);</span><br><span class="line">					setMethod.invoke(obj, convertValue); <span class="comment">// 调用setter方法设置内容</span></span><br><span class="line">				&#125;</span><br><span class="line">			&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 实现属性类型转换处理</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> type  属性类型，通过Field获取的</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> value 属性的内容，传入的都是字符串，需要将其变为指定类型</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> 转换后的数据</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">static</span> Object <span class="title">convertAttributeValue</span><span class="params">(String type, String value)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (<span class="string">"long"</span>.equals(type) || <span class="string">"Long"</span>.equals(type)) &#123; <span class="comment">// 长整型</span></span><br><span class="line">			<span class="keyword">return</span> Long.parseLong(value);</span><br><span class="line">		&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">"int"</span>.equals(type) || <span class="string">"java.lang.int"</span>.equals(type)) &#123;</span><br><span class="line">			<span class="keyword">return</span> Integer.parseInt(value);</span><br><span class="line">		&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">"double"</span>.equals(type) || <span class="string">"java.lang.double"</span>.equals(type)) &#123;</span><br><span class="line">			<span class="keyword">return</span> Double.parseDouble(value);</span><br><span class="line">		&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">"java.util.Date"</span>.equals(type)) &#123;</span><br><span class="line">			SimpleDateFormat sdf = <span class="keyword">null</span>;</span><br><span class="line">			<span class="keyword">if</span> (value.matches(<span class="string">"\\d&#123;4&#125;-\\d&#123;2&#125;-\\d&#123;2&#125;"</span>)) &#123; <span class="comment">// 日期类型</span></span><br><span class="line">				sdf = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd"</span>);</span><br><span class="line">			&#125; <span class="keyword">else</span> <span class="keyword">if</span> (value.matches(<span class="string">"\\d&#123;4&#125;-\\d&#123;2&#125;-\\d&#123;2&#125; \\d&#123;2&#125;:\\d&#123;2&#125;:\\d&#123;2&#125;"</span>)) &#123;</span><br><span class="line">				sdf = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</span><br><span class="line">			&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">new</span> Date();</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				<span class="keyword">return</span> sdf.parseObject(value);</span><br><span class="line">			&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">new</span> Date(); <span class="comment">// 当前日期</span></span><br><span class="line">			&#125;</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="keyword">return</span> value;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Company</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> String name;</span><br><span class="line">	<span class="keyword">private</span> Date creatDate;</span><br><span class="line">	<span class="comment">// 构造、setter、getter</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dept</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> String dname;</span><br><span class="line">	<span class="keyword">private</span> String loc;</span><br><span class="line">	<span class="keyword">private</span> Company company;</span><br><span class="line">	<span class="comment">// 构造、setter、getter</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Emp</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">long</span> empno;</span><br><span class="line">	<span class="keyword">private</span> String ename;</span><br><span class="line">	<span class="keyword">private</span> String job;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">double</span> salary;</span><br><span class="line">	<span class="keyword">private</span> Date hiredate;</span><br><span class="line">	<span class="keyword">private</span> Dept dept;</span><br><span class="line">	<span class="comment">// 构造、setter、getter</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
                
                <hr>
                <!-- Pager -->
                <ul class="pager">
                    
                        <li class="previous">
                            <a href="/article/卡诺图与“只出现一次的数字”问题/" data-toggle="tooltip" data-placement="top" title="卡诺图与“只出现一次的数字”问题">&larr; 上一篇</a>
                        </li>
                    
                    
                        <li class="next">
                            <a href="/article/jdk学习之路—反射机制的相关类/" data-toggle="tooltip" data-placement="top" title="反射机制的相关类【转载】">下一篇 &rarr;</a>
                        </li>
                    
                </ul>

                <br>

                <!--打赏-->
                
                <!--打赏-->

                <br>
                <!--分享-->
                
                <!--分享-->
                <br>                       
                
                <!-- require APlayer -->
                
            </div>
            
            <!-- Tabe of Content -->
            <!-- Table of Contents -->

  
    <style>
      span.toc-nav-number{
        display: none
      }
    </style>
  
    
      <aside id="sidebar">
        <div id="toc" class="toc-article">
        <strong class="toc-title">目录</strong>
        
          <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#定义"><span class="toc-nav-number">1.</span> <span class="toc-nav-text">&#x5B9A;&#x4E49;</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#获取一个类的实例化对象的三种方式"><span class="toc-nav-number">2.</span> <span class="toc-nav-text">&#x83B7;&#x53D6;&#x4E00;&#x4E2A;&#x7C7B;&#x7684;&#x5B9E;&#x4F8B;&#x5316;&#x5BF9;&#x8C61;&#x7684;&#x4E09;&#x79CD;&#x65B9;&#x5F0F;</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#通过反射实例化对象"><span class="toc-nav-number">3.</span> <span class="toc-nav-text">&#x901A;&#x8FC7;&#x53CD;&#x5C04;&#x5B9E;&#x4F8B;&#x5316;&#x5BF9;&#x8C61;</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#反射获取类的基本信息"><span class="toc-nav-number">4.</span> <span class="toc-nav-text">&#x53CD;&#x5C04;&#x83B7;&#x53D6;&#x7C7B;&#x7684;&#x57FA;&#x672C;&#x4FE1;&#x606F;</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#应用反射与简单java类对象属性的自动设置"><span class="toc-nav-number">5.</span> <span class="toc-nav-text">&#x5E94;&#x7528;&#xFF1A;&#x53CD;&#x5C04;&#x4E0E;&#x7B80;&#x5355;Java&#x7C7B;&#x5BF9;&#x8C61;&#x5C5E;&#x6027;&#x7684;&#x81EA;&#x52A8;&#x8BBE;&#x7F6E;</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#属性的自动设置"><span class="toc-nav-number">5.1.</span> <span class="toc-nav-text">&#x5C5E;&#x6027;&#x7684;&#x81EA;&#x52A8;&#x8BBE;&#x7F6E;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#单级属性配置"><span class="toc-nav-number">5.2.</span> <span class="toc-nav-text">&#x5355;&#x7EA7;&#x5C5E;&#x6027;&#x914D;&#x7F6E;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#多种数据类型的属性配置"><span class="toc-nav-number">5.3.</span> <span class="toc-nav-text">&#x591A;&#x79CD;&#x6570;&#x636E;&#x7C7B;&#x578B;&#x7684;&#x5C5E;&#x6027;&#x914D;&#x7F6E;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#级联对象实例化"><span class="toc-nav-number">5.4.</span> <span class="toc-nav-text">&#x7EA7;&#x8054;&#x5BF9;&#x8C61;&#x5B9E;&#x4F8B;&#x5316;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#级联属性设置"><span class="toc-nav-number">5.5.</span> <span class="toc-nav-text">&#x7EA7;&#x8054;&#x5C5E;&#x6027;&#x8BBE;&#x7F6E;</span></a></li></ol></li></ol>
        
        </div>
      </aside>
    

                
            <!-- Sidebar Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5><a href="/tags/">标签</a></h5>
                    <div class="tags">
                       
                          <a class="tag" href="/tags/#jdk学习之路" title="jdk学习之路">jdk学习之路</a>
                        
                    </div>
                </section>
                

                <!-- Friends Blog -->
				<!--
                
                <hr>
                <h5>朋友们</h5>
                <ul class="list-inline">

                    
                        <li><a href="https://tyzhang.top/" target="_blank">ztygalaxy</a></li>
                    
                        <li><a href="http://www.yctang.club/" target="_blank">yctang</a></li>
                    
                        <li><a href="https://dolnw.github.io" target="_blank">JCWang</a></li>
                    
                </ul>
                
				-->
            </div>
        </div>
    </div>
</article>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script>
    async("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js",function(){
        anchors.options = {
          visible: 'hover',
          placement: 'left',
          icon: ''
        };
        anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
    })
</script>
<style>
    /* place left on bigger screen */
    @media all and (min-width: 800px) {
        .anchorjs-link{
            position: absolute;
            left: -0.75em;
            font-size: 1.1em;
            margin-top : -0.1em;
        }
    }
</style>


<!-- chrome Firefox 中文锚点定位失效-->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<!-- smooth scroll behavior polyfill  -->
<script type="text/javascript" src="/js/smoothscroll.js"></script>
<script>
        $('#toc').on('click','a',function(a){
            // var isChrome = window.navigator.userAgent.indexOf("Chrome") !== -1;
            // console.log(window.navigator.userAgent,isChrome)
                // if(isChrome) {
                    // console.log(a.currentTarget.outerHTML);
                    // console.log($(a.currentTarget).attr("href"));
                    //跳转到指定锚点
                    // document.getElementById(a.target.innerText.toLowerCase()).scrollIntoView(true);
                    document.getElementById($(a.currentTarget).attr("href").replace("#","")).scrollIntoView({behavior: 'smooth' });
                // }
        })  
</script>


    <!-- Footer -->
    <!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <ul class="list-inline text-center">
                
                
                
				
                

                

                
                    <li>
                        <a target="_blank"  href="https://github.com/songzblink">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-github fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                

                </ul>
                <p class="copyright text-muted">
                    Copyright &copy; 宋正兵 2021 
                    <br>
                    Theme by <a href="http://www.huweihuang.com">Huwei Huang</a>
                    re-Ported by <a href="https://github.com/ztygalaxy">ztygalaxy</a>
					
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/hux-blog.min.js"></script>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- 
     Because of the native support for backtick-style fenced code blocks 
     right within the Markdown is landed in Github Pages, 
     From V1.6, There is no need for Highlight.js, 
     so Huxblog drops it officially.

     - https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0  
     - https://help.github.com/articles/creating-and-highlighting-code-blocks/    
-->
<!--
    <script>
        async("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function(){
            hljs.initHighlightingOnLoad();
        })
    </script>
    <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet">
-->


<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("zbsong.top/js/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>


<!-- Google Analytics -->




<!-- Baidu Tongji -->






	<a id="rocket" href="#top" class=""></a>
	<script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
    <script type="text/javascript" src="/js/toc.js?v=1.0.0" async=""></script>
<!-- Image to hack wechat -->
<img src="zbsong.top/img/icon_wechat.png" width="0" height="0" />
<!-- Migrate from head to bottom, no longer block render and still work -->

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<!--
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"></script>
</body>

</html>
